package aidn.animation.text 
{
	import aidn.animation.utils.Hide;
	import aidn.animation.utils.Utils;
	import caurina.transitions.Tweener;
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	
	
	public class TextBitmap extends Sprite
	{
		private var _text :Text;
		
		public function TextBitmap() 
		{
			
		}
		
		/**
		 * 初期化します(ビットマップ化したマージン"0"のテキストを生成)
		 * @param	text
		 * @param	font
		 * @param	color
		 * @param	size
		 */
		public function init ( text :String, font :String, color :uint = 0, size :int = 96 ) :void
		{
			_text = new Text(font, color, size);
			_text.text = text;
			
			var tmp :BitmapData = new BitmapData(_text.width, _text.height, true, 0x0);
			tmp.draw(_text);
			var rect :Rectangle = tmp.getColorBoundsRect(0xff000000, 0x00000000, false);
			
			if (rect.width <= 0 || rect.height <= 0)
			{
				rect.width  = _text.width;
				rect.height = _text.height;
			}
			
			var bmd :BitmapData = new BitmapData(rect.width, rect.height, true, 0x0);
			bmd.copyPixels(tmp, rect, new Point());
			
			tmp.dispose();
			tmp = null;
			
			var bmp :Bitmap = new Bitmap(bmd);
			bmp.x = - int(bmp.width  / 2);
			bmp.y = - int(bmp.height / 2);
			bmp.smoothing = true;
			addChild(bmp);
		}
		
		/**
		 * 表示アニメーション
		 */
		public function show ( type :int = 0, hideTime :Number = -1 ) :void
		{
			var pX  :Number = x;
			var pY  :Number = y;
			var sX  :Number = scaleX;
			var sY  :Number = scaleY;
			var al  :Number = alpha;
			var rot :Number = rotation;
			
			switch ( type )
			{
			case 0:
				scaleX = scaleY = 0;
				Tweener.addTween( this, { scaleX: sX, scaleY: sY, time: 0.5, transition: "easeOutElastic" } );
				break;
			case 1:
				rotation = rot + Utils.rand(50, 100);
				Tweener.addTween( this, { rotation: rot, time: 0.5, transition: "easeOutElastic" } );
				break;
			case 2:
				x = x + Utils.rand(-50, 50);
				Tweener.addTween( this, { x: pX, time: 0.5, transition: "easeOutElastic" } );
				break;
			case 3:
				y = y + Utils.rand(-50, 50);
				Tweener.addTween( this, { y: pY, time: 0.5, transition: "easeOutElastic" } );
				break;
			default:
				//rotation = rot - Utils.rand(50, 100);
				//Tweener.addTween( this, { rotation: rot, time: 0.5, transition: "easeOutElastic" } );
				alpha = 0;
				Tweener.addTween( this, { alpha: al, time: 0.5, transition: "linear" } );
				break;
			}
			
			
			
			// 破棄
			if (0 < hideTime) Tweener.addTween( this, { alpha: 0, time: 0.1, delay: hideTime, onComplete: _kill, transition: "linear" } );
		}
		
		private function _kill ( ) :void
		{
			var t :TextBitmap = this;
			
			Hide.start( t );
			if (t.parent) t.parent.removeChild(t);
			t = null;
		}
	}
}